<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useDietStore } from '../stores/diet'
import { recognizeFoodImage } from '../services/cozeApi'

/**
 * 获取饮食数据存储
 */
const dietStore = useDietStore()

/**
 * 组件状态
 */
const activeTab = ref('camera') // 'camera' 或 'gallery'
const isLoading = ref(false)
const showResult = ref(false)
const showCamera = ref(false)
const videoElement = ref(null)
const canvasElement = ref(null)
const mediaStream = ref(null)
const capturedImage = ref(null)

/**
 * 食物识别结果
 */
const recognitionResult = reactive({
  name: '',
  calories: 0,
  image: '',
  nutrition: {
    protein: 0,
    fat: 0,
    carbs: 0,
    fiber: 0
  },
  tips: '',
  similarFoods: []
})

/**
 * 切换标签页
 * @param {string} tab - 标签名称
 */
const switchTab = (tab) => {
  activeTab.value = tab
  
  if (tab === 'camera') {
    if (!showCamera.value) {
      initCamera()
    }
  } else {
    stopCamera()
  }
}

/**
 * 初始化相机
 */
const initCamera = async () => {
  try {
    const constraints = {
      video: {
        facingMode: 'environment',
        width: { ideal: 1280 },
        height: { ideal: 720 }
      }
    }
    
    const stream = await navigator.mediaDevices.getUserMedia(constraints)
    mediaStream.value = stream
    
    if (videoElement.value) {
      videoElement.value.srcObject = stream
      showCamera.value = true
    }
  } catch (error) {
    console.error('获取摄像头失败:', error)
    alert('无法访问摄像头，请检查权限设置。')
  }
}

/**
 * 停止相机
 */
const stopCamera = () => {
  if (mediaStream.value) {
    mediaStream.value.getTracks().forEach(track => {
      track.stop()
    })
    mediaStream.value = null
    showCamera.value = false
    
    if (videoElement.value) {
      videoElement.value.srcObject = null
    }
  }
}

/**
 * 切换前后摄像头
 */
const toggleCamera = async () => {
  const currentFacingMode = mediaStream.value?.getVideoTracks()[0]?.getSettings()?.facingMode
  const newFacingMode = currentFacingMode === 'environment' ? 'user' : 'environment'
  
  stopCamera()
  
  try {
    const constraints = {
      video: {
        facingMode: newFacingMode,
        width: { ideal: 1280 },
        height: { ideal: 720 }
      }
    }
    
    const stream = await navigator.mediaDevices.getUserMedia(constraints)
    mediaStream.value = stream
    
    if (videoElement.value) {
      videoElement.value.srcObject = stream
    }
  } catch (error) {
    console.error('切换摄像头失败:', error)
    // 如果切换失败，重新初始化默认摄像头
    initCamera()
  }
}

/**
 * 打开文件选择器
 */
const openFilePicker = () => {
  const fileInput = document.createElement('input')
  fileInput.type = 'file'
  fileInput.accept = 'image/*'
  fileInput.onchange = (event) => {
    const file = event.target.files[0]
    if (file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        capturedImage.value = e.target.result
        recognizeFood(capturedImage.value)
      }
      reader.readAsDataURL(file)
    }
  }
  fileInput.click()
}

/**
 * 拍照
 */
const takePhoto = () => {
  if (!videoElement.value || !canvasElement.value) return
  
  const video = videoElement.value
  const canvas = canvasElement.value
  const context = canvas.getContext('2d')
  
  // 设置canvas尺寸与视频一致
  canvas.width = video.videoWidth
  canvas.height = video.videoHeight
  
  // 绘制视频帧到canvas
  context.drawImage(video, 0, 0, canvas.width, canvas.height)
  
  // 获取图片数据
  capturedImage.value = canvas.toDataURL('image/jpeg')
  
  // 识别食物
  recognizeFood(capturedImage.value)
}

/**
 * 识别食物
 * @param {string} imageData - 图片数据URL
 */
const recognizeFood = async (imageData) => {
  isLoading.value = true
  showResult.value = false
  
  try {
    // 去除数据URL的前缀，获取纯base64数据
    const base64Data = imageData.split(',')[1]
    
    // 调用Coze API服务
    const result = await recognizeFoodImage(base64Data)
    
    if (result.success) {
      // 更新识别结果
      recognitionResult.name = result.data.name
      recognitionResult.calories = result.data.calories
      recognitionResult.image = imageData
      recognitionResult.nutrition = result.data.nutrition
      recognitionResult.tips = result.data.tips
      recognitionResult.similarFoods = result.data.similarFoods
      
      showResult.value = true
      stopCamera() // 显示结果时停止相机
    } else {
      throw new Error('识别失败')
    }
  } catch (error) {
    console.error('识别食物失败:', error)
    alert('识别失败，请重试。')
  } finally {
    isLoading.value = false
  }
}

/**
 * 添加到今日饮食
 */
const addToMeal = () => {
  dietStore.addMealItem({
    id: Date.now(),
    name: recognitionResult.name,
    calories: recognitionResult.calories,
    image: recognitionResult.image,
    nutrition: recognitionResult.nutrition,
    mealType: 'lunch' // 默认添加到午餐，实际项目中可以让用户选择
  })
  
  alert(`已将${recognitionResult.name}添加到今日午餐`)
}

/**
 * 重新识别
 */
const recognizeAgain = () => {
  showResult.value = false
  capturedImage.value = null
  
  if (activeTab.value === 'camera') {
    initCamera()
  }
}

/**
 * 获取当前时间
 */
const getCurrentTime = () => {
  const now = new Date()
  const hours = now.getHours().toString().padStart(2, '0')
  const minutes = now.getMinutes().toString().padStart(2, '0')
  return `${hours}:${minutes}`
}

const currentTime = ref(getCurrentTime())

// 组件挂载时初始化
onMounted(() => {
  // 自动初始化相机
  if (activeTab.value === 'camera') {
    initCamera()
  }
  
  // 更新时间
  const timeInterval = setInterval(() => {
    currentTime.value = getCurrentTime()
  }, 60000)
  
  // 清除定时器
  onUnmounted(() => {
    clearInterval(timeInterval)
    stopCamera()
  })
})
</script>

<template>
  <div class="food-recognition-page">
    <!-- 导航栏 -->
    <div class="nav-bar">
      <div class="nav-title">食物识别</div>
      <button class="nav-btn"><i class="fas fa-history"></i></button>
    </div>
    
    <!-- 内容区域 -->
    <div class="content-container">
      <div class="recognition-container">
        <!-- 标签切换 -->
        <div class="tabs">
          <div 
            class="tab" 
            :class="{ active: activeTab === 'camera' }"
            @click="switchTab('camera')"
          >
            拍照识别
          </div>
          <div 
            class="tab" 
            :class="{ active: activeTab === 'gallery' }"
            @click="switchTab('gallery')"
          >
            相册选择
          </div>
        </div>
        
        <!-- 加载中 -->
        <div v-if="isLoading" class="loading-container">
          <div class="spinner"></div>
          <p>识别中...</p>
        </div>
        
        <!-- 相机视图 -->
        <template v-else-if="!showResult">
          <div class="camera-view-container" v-if="activeTab === 'camera' && showCamera">
            <video 
              ref="videoElement"
              autoplay
              playsinline
              muted
              style="width: 100%; height: 100%; object-fit: cover;"
            ></video>
            
            <div class="camera-overlay">
              <div class="camera-top-controls">
                <button class="camera-control-btn"><i class="fas fa-bolt"></i></button>
                <button class="camera-control-btn"><i class="fas fa-ellipsis-h"></i></button>
              </div>
              
              <div class="camera-bottom-controls">
                <button class="camera-control-btn" @click="openFilePicker">
                  <i class="fas fa-images"></i>
                </button>
                <div class="shutter-btn" @click="takePhoto">
                  <div class="shutter-btn-inner"></div>
                </div>
                <button class="camera-control-btn" @click="toggleCamera">
                  <i class="fas fa-sync-alt"></i>
                </button>
              </div>
            </div>
          </div>
          
          <div v-else-if="activeTab === 'gallery'" class="gallery-container">
            <div class="upload-box" @click="openFilePicker">
              <i class="fas fa-cloud-upload-alt"></i>
              <p>点击选择图片</p>
            </div>
          </div>
          
          <!-- 隐藏的canvas用于处理拍照 -->
          <canvas ref="canvasElement" style="display: none;"></canvas>
        </template>
        
        <!-- 识别结果 -->
        <template v-else>
          <div class="food-result">
            <div class="food-result-header">
              <img :src="recognitionResult.image" :alt="recognitionResult.name" class="food-result-img">
              <div>
                <div class="food-result-name">{{ recognitionResult.name }}</div>
                <div class="food-result-calories">约 {{ recognitionResult.calories }} 卡路里 / 份</div>
              </div>
            </div>
            
            <div class="nutrition-list">
              <div class="nutrition-item">
                <div class="nutrition-name">蛋白质</div>
                <div class="nutrition-value">{{ recognitionResult.nutrition.protein }}g</div>
              </div>
              <div class="nutrition-item">
                <div class="nutrition-name">脂肪</div>
                <div class="nutrition-value">{{ recognitionResult.nutrition.fat }}g</div>
              </div>
              <div class="nutrition-item">
                <div class="nutrition-name">碳水化合物</div>
                <div class="nutrition-value">{{ recognitionResult.nutrition.carbs }}g</div>
              </div>
              <div class="nutrition-item">
                <div class="nutrition-name">纤维素</div>
                <div class="nutrition-value">{{ recognitionResult.nutrition.fiber }}g</div>
              </div>
            </div>
          </div>
          
          <!-- 健康提示 -->
          <div class="tips-container">
            <div class="tips-title">
              <i class="fas fa-lightbulb"></i> 健康小提示
            </div>
            <p class="text-sm text-gray-600">{{ recognitionResult.tips }}</p>
          </div>
          
          <!-- 相似食物推荐 -->
          <div>
            <div class="text-sm font-semibold mb-2">相似食物推荐</div>
            <div class="similar-foods">
              <div 
                v-for="food in recognitionResult.similarFoods" 
                :key="food.id"
                class="similar-food-item"
              >
                <img :src="food.image" class="similar-food-img" :alt="food.name">
                <div class="similar-food-name">{{ food.name }}</div>
                <div class="text-xs text-green-500">{{ food.calories }} 卡路里</div>
              </div>
            </div>
          </div>
          
          <!-- 操作按钮 -->
          <div class="action-buttons">
            <button class="btn-primary action-btn" @click="addToMeal">添加到今日饮食</button>
            <button class="btn-outline action-btn" @click="recognizeAgain">重新识别</button>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<style scoped>
.food-recognition-page {
  padding-bottom: 80px;
}

/* 导航栏 */
.nav-bar {
  padding: var(--spacing-md);
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: white;
  border-bottom: 1px solid #f0f0f0;
}

.nav-title {
  font-size: var(--font-size-xl);
  font-weight: 600;
  color: #333;
}

.nav-btn {
  background: none;
  border: none;
  color: #333;
  font-size: var(--font-size-lg);
  cursor: pointer;
}

/* 加载动画 */
.loading-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(34, 197, 94, 0.2);
  border-radius: 50%;
  border-top-color: #22C55E;
  animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 内容容器 */
.content-container {
  padding: var(--spacing-md);
}

.recognition-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* 标签切换 */
.tabs {
  display: flex;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: var(--spacing-md);
}

.tab {
  flex: 1;
  text-align: center;
  padding: var(--spacing-sm);
  font-size: var(--font-size-sm);
  font-weight: 600;
  color: #6B7280;
  cursor: pointer;
  transition: color 0.2s ease;
}

.tab:hover {
  color: #22C55E;
}

.tab.active {
  color: #22C55E;
  border-bottom: 2px solid #22C55E;
}

/* 相机视图 */
.camera-view-container {
  width: 100%;
  aspect-ratio: 4/3;
  background-color: #000;
  border-radius: var(--card-border-radius);
  overflow: hidden;
  position: relative;
  margin-bottom: var(--spacing-md);
}

.camera-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: var(--spacing-md);
}

.camera-top-controls {
  display: flex;
  justify-content: space-between;
}

.camera-control-btn {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  border: none;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.camera-control-btn:hover {
  background-color: rgba(0, 0, 0, 0.5);
}

.camera-bottom-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.shutter-btn {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  background-color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.shutter-btn:hover {
  transform: scale(1.05);
}

.shutter-btn-inner {
  width: 56px;
  height: 56px;
  border-radius: 50%;
  border: 2px solid #f0f0f0;
}

/* 相册视图 */
.gallery-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-bottom: var(--spacing-md);
}

.upload-box {
  width: 100%;
  aspect-ratio: 4/3;
  border: 2px dashed #e5e7eb;
  border-radius: var(--card-border-radius);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  background-color: #f9fafb;
  transition: background-color 0.2s ease;
}

.upload-box:hover {
  background-color: #f0f2f5;
}

.upload-box i {
  font-size: 48px;
  color: #d1d5db;
  margin-bottom: var(--spacing-md);
}

.upload-box p {
  font-size: var(--font-size-base);
  color: #6b7280;
}

/* 识别结果 */
.food-result {
  border-radius: var(--card-border-radius);
  overflow: hidden;
  margin-bottom: var(--spacing-md);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.food-result-header {
  display: flex;
  align-items: center;
  background-color: #DCFCE7;
  padding: var(--spacing-md);
}

.food-result-img {
  width: 80px;
  height: 80px;
  border-radius: var(--spacing-sm);
  object-fit: cover;
  margin-right: var(--spacing-md);
  border: 3px solid white;
}

.food-result-name {
  font-size: var(--font-size-lg);
  font-weight: 600;
  margin-bottom: 4px;
  color: #333;
}

.food-result-calories {
  font-size: var(--font-size-sm);
  color: #22C55E;
  font-weight: 500;
}

.nutrition-list {
  padding: var(--spacing-md);
  background-color: white;
}

.nutrition-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--spacing-sm) 0;
  border-bottom: 1px solid #f0f0f0;
}

.nutrition-item:last-child {
  border-bottom: none;
}

.nutrition-name {
  font-size: var(--font-size-sm);
  color: #374151;
}

.nutrition-value {
  font-size: var(--font-size-sm);
  font-weight: 500;
  color: #111827;
}

/* 健康提示 */
.tips-container {
  background-color: #F9FAFB;
  border-radius: var(--card-border-radius);
  padding: var(--spacing-md);
  margin-bottom: var(--spacing-md);
}

.tips-title {
  font-size: var(--font-size-base);
  font-weight: 600;
  margin-bottom: var(--spacing-sm);
  display: flex;
  align-items: center;
  color: #333;
}

.tips-title i {
  color: #FDBA74;
  margin-right: var(--spacing-xs);
}

/* 相似食物 */
.similar-foods {
  display: flex;
  overflow-x: auto;
  padding-bottom: var(--spacing-sm);
  margin: var(--spacing-md) 0;
  scrollbar-width: none; /* Firefox */
  gap: var(--spacing-sm);
}

.similar-foods::-webkit-scrollbar {
  display: none; /* Chrome, Safari, Edge */
}

.similar-food-item {
  flex: 0 0 100px;
  text-align: center;
  transition: transform 0.2s ease;
}

.similar-food-item:hover {
  transform: translateY(-2px);
}

.similar-food-img {
  width: 100px;
  height: 100px;
  border-radius: var(--spacing-sm);
  object-fit: cover;
  margin-bottom: var(--spacing-sm);
}

.similar-food-name {
  font-size: var(--font-size-xs);
  color: #374151;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  margin-top: var(--spacing-xl);
  gap: var(--spacing-sm);
}

.action-btn {
  flex: 1;
}

.btn-primary {
  display: inline-block;
  padding: var(--spacing-sm) var(--spacing-md);
  background-color: #22C55E;
  color: white;
  border: none;
  border-radius: 8px;
  font-weight: 500;
  font-size: var(--font-size-sm);
  text-align: center;
  cursor: pointer;
  transition: all 0.2s ease;
  width: 100%;
}

.btn-primary:hover {
  background-color: #16A34A;
}

.btn-outline {
  display: inline-block;
  padding: var(--spacing-sm) var(--spacing-md);
  background-color: transparent;
  color: #22C55E;
  border: 1px solid #22C55E;
  border-radius: 8px;
  font-weight: 500;
  font-size: var(--font-size-sm);
  text-align: center;
  cursor: pointer;
  transition: all 0.2s ease;
  width: 100%;
}

.btn-outline:hover {
  background-color: rgba(34, 197, 94, 0.1);
}

/* 平板和桌面布局优化 */
@media (min-width: 640px) {
  .content-container {
    padding: 0 var(--container-padding);
  }
  
  .camera-view-container,
  .upload-box {
    max-width: 600px;
    margin-left: auto;
    margin-right: auto;
  }
  
  .food-result,
  .tips-container {
    max-width: 600px;
    margin-left: auto;
    margin-right: auto;
  }
  
  .action-buttons {
    max-width: 600px;
    margin-left: auto;
    margin-right: auto;
  }
}

@media (min-width: 768px) {
  .similar-foods {
    flex-wrap: wrap;
    justify-content: flex-start;
    overflow-x: visible;
  }
  
  .similar-food-item {
    margin-bottom: var(--spacing-md);
  }
  
  .action-buttons {
    gap: var(--spacing-md);
  }
  
  .camera-control-btn {
    width: 48px;
    height: 48px;
  }
  
  .shutter-btn {
    width: 72px;
    height: 72px;
  }
  
  .shutter-btn-inner {
    width: 64px;
    height: 64px;
  }
}
</style> 